/*=============================================================================
    test/placementTest.js
    Copyright (C) 2008-2009, Donald W. Griffin
    All rights reserved.
    [MIT license :: see license.txt for details]
=============================================================================*/
$module("test.placementTest");

$requires("jibits.popup");
$requires("test.base");

$namespace(test, {

PlacementTester : $class(jibits.Popup, function ()
{
    function angle (origin, pt)
    {
        return Math.atan2(pt.x - origin.x, pt.y - origin.y) + Math.PI;
    }

    function percent (n, d)
    {
        return Math.round((n * 1000.0) / d) / 10.0;
    }

    function placements (r, pt)
    {
        var origin = $point((r.L() + r.R()) / 2, (r.T() + r.B()) / 2);
        var aLT = angle(origin, r.TL());
        var aLB = angle(origin, r.BL());
        var aRT = angle(origin, r.TR());
        var aRB = angle(origin, r.BR());
        var a = angle(origin, pt), dx = pt.x - r.L(), dy = pt.y - r.T();
        var quartile = "T";

        if (a >= aLT)
        {
            if (a < aLB)
                quartile = "L";
            else if (a < aRB)
                quartile = "B";
            else if (a < aRT)
                quartile = "R";
        }

        var he, ve, hr, vr;

        if (quartile == "L")
            { hr = "0%"; he = "100%"; }
        else if (quartile == "R")
            { hr = "100%"; he = "0%"; }
        else
            { hr = "0%+" + dx; he = (100 - percent(dx, r.W())) + "%"; }

        if (quartile == "T")
            { vr = "0%"; ve = "100%"; }
        else if (quartile == "B")
            { vr = "100%"; ve = "0%"; }
        else
            { vr = "0%+" + dy; ve = (100 - percent(dy, r.H())) + "%"; }

        var ret = { elp : he+","+ve, refp : hr+","+vr };

        return ret;
    }

    return (
    {
        ctor : function (id, config)
        {
            $super(arguments).call(this, id);

            this.ref = config.ref;

            this.listen(this.ref, this.onMouseMove.bind(this), "mousemove");
            this.listen(this.ref, this.onMouseOut.bind(this), "mouseout");
        },

        onMouseMove : function (ev)
        {
            var r = jibits.getTotalOffsetRect(this.ref);
            var pl = placements(r, $point(ev.pageX, ev.pageY));

            this.placeAdjacent(pl.elp, this.ref, pl.refp);
            if (!this.isVisible())
            {
                this.moveToTop();
                this.show();
            }
        },

        onMouseOut : function (ev)
        {
            if (!ev.ctrlKey)
                this.hide();
        }
    });
}()) // PlacementTester

}) // namespace test
